package vfs.client.command;

import vfs.client.Locale;
import vfs.client.rmi.ClientRmiManager;
import vfs.common.Regex;
import vfs.common.command.AbstractCommand;
import vfs.common.command.Command;
import vfs.common.tty.Tty;

import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.regex.Matcher;

/**
 * Connecting with server. Syntax: connect host[:port] UserName
 * <p/>
 * User: serge
 * Date: 20.11.13
 * Time: 18:32
 */
public class ConnectCommand extends AbstractCommand implements Command
{
    @Override
    public void execute()
    {
        String host;
        int port = 0;
        String user;

        if (params.length != 3)
        {
            Tty.println(vfs.common.Locale.CMD_EXC_WRONG_PARAMS);
            return;
        }

        /** my-hostname_dev.local[:65535] */
        String hostnamePortMask = "([\\w-\\.]{2,}?)(:(\\d{4,5}))?";
        Matcher matcherPort = Regex.getMatcherStringMask(params[1], hostnamePortMask, false);

        /* if port:hostname does not specified correctly */
        if (!matcherPort.matches())
        {
            Tty.println(Locale.CMD_CONNECT_EXC_WRONG_HOSTNAME_PORT);
            return;
        }
        else
        {
            host = matcherPort.group(1);

            /* got port */
            String portString = matcherPort.group(3);

            if (portString != null)
            {
                try
                {
                    port = Integer.parseInt(portString);

                    if (port > 65535)
                    {
                        Tty.println(Locale.CMD_CONNECT_EXC_WRONG_HOSTNAME_PORT);
                        return;
                    }
                }
                catch (NumberFormatException e)
                {
                    e.printStackTrace();
                    Tty.println(Locale.CMD_CONNECT_EXC_WRONG_HOSTNAME_PORT);
                    return;
                }
            }

            user = params[2];
        }

        try
        {
            ClientRmiManager.getInstance().startSession(host, port, user);

            if (ClientRmiManager.getInstance().isSessionStarted())
            {
                String hostTty = port == 0 ? host : host.concat(":").concat(String.valueOf(port));

                Tty.setHostname(hostTty);
                Tty.setUsername(user);
                Tty.setPath("");

                Tty.println("Connected OK");
            }
            else
            {
                Tty.println("Connection failed: such user already registered");
            }
        }
        catch (RemoteException | NotBoundException | AlreadyBoundException e)
        {
            Tty.println(String.format(Locale.CMD_CONNECT_EXC_FORMAT, e.getMessage()));
            //            e.printStackTrace();
        }
    }
}
